/**
 * Created by neal on 11/22/16.
 */

var Config = {
    createUrl: '/api/goods',
    updateUrl: '/api/goods',
    deleteUrl: '/api/goods',
    selectUrl: '/api/goods',
    deleteAlbumUrl: '/api/goods/album',
    selectCompanyUrl: '/api/admin/company/providers'
};

var ConfigCategory = {
    createUrl: '/api/admin/categories/post',
    updateUrl: '/api/admin/categories/update',
    deleteUrl: '/api/admin/categories/delete',
    selectUrl: '/api/admin/categories/get'
};

var ConfigAttribute = {
    selectUrl: '/api/goodsAttribute'
};
var ConfigAttributeLink = {
    updateUrl: '/api/goodsAttributeLink',
    selectByGoodsIdUrl: '/api/goodsAttributeLink/goodsID/{goodsID}',
    updateByGoodsIdUrl: '/api/goodsAttrLinkUpdateByGoodsId'

}

var ConfigType = {
    selectUrl: '/api/admin/goodsType/get'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});

var ue = UE.getEditor('editor');
var ueAlbum = UE.getEditor('editorAlbum');

$().ready(function () {
    $("#datepicker").datepicker({keyboardNavigation: !1, forceParse: !1, autoclose: !0});
    $(".fancybox").fancybox({openEffect: "none", closeEffect: "none"});
    $('input:radio[name="goodsGetType"]').filter('[value="'+$("input[id=goodsGetType]").val()+'"]').attr('checked', true);
    $.ajax(
        {
            url: ConfigCategory.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true" ');
                    if (goodsCategoryIdChecked == category.categoryId) {
                        categories.push('selected="selected">');
                    } else {
                        categories.push('>');
                    }
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#categoryId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $.ajax(
        {
            url: ConfigCategory.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#goodsBrandId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "请选择分类");
    $('#submitCategoryCreate').click(function () {
        if ($("#goodsPayType").val() == 0) {
            if (Number($("input[name=goodsScreenPrice]").val()) < Number($("input[name=goodsRealPrice]").val())) {
                alert("卖出价必须大于进货价，请输入正确的价格！");
                return false;
            }
        }
        var oneLevel=Number($("input[id=oneLevel]").val());
        var twoLevel=Number($("input[id=twoLevel]").val());
        var areaLevel=Number($("input[id=areaLevel]").val());
        var cityLevel=Number($("input[id=cityLevel]").val());
        var provinceLevel=Number($("input[id=provinceLevel]").val());
        var rtLevel=Number($("input[id=rtLevel]").val());
        if (oneLevel + twoLevel + areaLevel + cityLevel + provinceLevel + rtLevel > 100){
            toastr.error("请正确输入比例");
            return false;
        }
        $.ajax({
            url:"/api/admin/rebateRatio",
            type: "PUT",
            data: {goodsId: $("#goodsId").val(),oneLevel:oneLevel,twoLevel:twoLevel,
                areaLevel:areaLevel,cityLevel:cityLevel,provinceLevel:provinceLevel,rtLevel:rtLevel},
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success("返利比例创建成功!", data.title);
            }
        });
        $("#ajaxform").validate({
            rules: {
                categoryId: {
                    selectcheck: true
                }
            }
        });
        if ($('#ajaxform').valid()) {
            var postData = $('#ajaxform').serializeArray();
            $.ajax(
                {
                    url: Config.updateUrl,
                    type: "PUT",
                    data: postData,
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        toastr.success(data.msg, data.title);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastr.error(errorThrown, textStatus);
                    }
                });
        }
        return false;
    });


    // providers
    $.ajax(
        {
            url: Config.selectCompanyUrl,
            type: "GET",
            // data: {companyType: 8},
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">供货商</option>');
                data.data.map(function (company) {
                    categories.push('<option value="');
                    categories.push(company.companyId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(company.companyName);
                    categories.push('</option>');
                });
                $("#goodsProviderId").html(categories.join(''));
                $("#goodsProviderId").val($("#goodsProviderIdTemp").val());

            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });


    $('#submitCategoryDetail').click(function () {
        $.ajax(
            {
                url: Config.updateUrl,
                type: "PUT",
                data: {goodsId: $("#goodsId").val(), goodsDetail: getContent()},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        return false;
    });

    $.ajax(
        {
            url: ConfigType.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true"  >商品类型</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.typeId);
                    categories.push('" ');
                    if (goodsTypeIdChecked == category.typeId) {
                        categories.push('selected="selected" ');
                    }
                    categories.push('hassubinfo="true" id="' + category.typeId + '">');
                    categories.push(category.typeName);
                    categories.push('</option>');
                });
                $("#typeId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $('#buttonGoback').click(function () {
        history.go(-1);
        location.reload();
        return false;
    });

    ue.addListener("ready", function () {
        // editor准备好之后才可以使用
        ue.setContent(goodsDetailChecked);

    });

    getAttrList();
    $('#submitAttrLike').click(getAttrJson);

    if (Number($("#goodsScreenPrice").val()) > 0) {
        $("#discount").text(($("#goodsRealPrice").val() / $("#goodsScreenPrice").val()).toFixed(2) * 100);
    }
});
function getContent() {
    return ue.getContent();
}
ue.ready(function () {
    ue.execCommand('serverparam', {
        'goodsId': $("#goodsId").val(),
        'imageType': 0
    });
});
ueAlbum.ready(function () {
    ueAlbum.execCommand('serverparam', {
        'goodsId': $("#goodsId").val(),
        'imageType': 1
    });
});


function getAttrJson() {
    var params = "";
    var jsonAttr = [];
    var jsonCheckBox = [];
    var json_real_price = [];
    $("input", $("#attribute-list")).each(function () {
        if ($(this).val() != "" && $(this).val().length > 0 && $(this).attr('name') == 'attr-text') {
            jsonAttr.push(($(this).attr("id") == "" ? "" : ('"id":' + $(this).attr("id") + ',')) +
                '"goodsId":' + $("#goodsId").val() + ',' +
                '"attrId":' + $(this).attr("attrId") + ',' +
                '"attrValue":"' + $(this).attr("attrValue").trim() + '",' +
                '"extraPrice":' + $(this).val());
            return;
        }
        if ($(this).attr('name') == "attr-checkbox") {
            jsonCheckBox.push('"attrShow":' + ($(this).prop("checked") ? 1 : 0 ) + ',');
            return;
        }
        if ($(this).attr('name') == "attrExtraPrice") {
            json_real_price.push(
                ' ,"realExtraPrice":' + $(this).val() + ",");
            return;
        }

    });


    for (var i = 0; i < jsonCheckBox.length; i++) {
        switch (i) {
            case 0:
                params = "[{" + jsonCheckBox[i] + json_real_price[i] + jsonAttr[i] + "},";
                break;
            case jsonCheckBox.length - 1:
                params += "{" + jsonCheckBox[i] + json_real_price[i] + jsonAttr[i] + "}]";
                break;
            default:
                params += "{" + jsonCheckBox[i] + json_real_price[i] + jsonAttr[i] + "},";
                break;
        }
    }

    if ($('#typeId option:selected').val() <= 0) {

        $.ajax(
            {
                url: ConfigAttributeLink.updateByGoodsIdUrl,
                type: "PUT",
                data: {goodsId: $("#goodsId").val()},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
    } else
        $.ajax(
            {
                url: ConfigAttributeLink.updateUrl,
                type: "PUT",
                data: {attrJson: params.replace('\n', '')},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });

    return false;
}

function getAttrList() {
    var id = $('#typeId option:selected').val();
    $.ajax(
    {
        url: ConfigAttribute.selectUrl,
        type: "GET",
        dataType: "json",
        data: {typeId: id},
        async: false,
        success: function (data) {
            var goodsAttributes = [];
            $.each(data.data,function (i, v) {
                goodsAttributes.push('<div class="form-group">');
                goodsAttributes.push('<label class="col-sm-2 control-label" id="' + v.attrId + '">' + v.attrName + '</label>');
                goodsAttributes.push('<div class="col-sm-10">');
                var attrValues = v.attrValues.split('\n');
                $.each(attrValues, function (n, o) {
                    goodsAttributes.push('<div class="form-inline">');
                    goodsAttributes.push('<div class="checkbox col-sm-2 control-label" >');
                    goodsAttributes.push('<label><input name="attr-checkbox"  type="checkbox"  ');
                    o = o.replace(/[\n\r]/,"");
                    var ab = checkAndFindAttributeLink(v.attrId, o);
                    // console.log("ab", ab)
                    if (ab.attrShow && ab.attrShow == 1) {
                        goodsAttributes.push(' checked="checked"');
                    }
                    goodsAttributes.push(' >' + o + '</div>');

                    goodsAttributes.push('<div class="form-group">');
                    goodsAttributes.push('<div class="col-sm-10">');
                    var extraPrice = 0;
                    var realExtraPrice = 0;
                    if(ab.extraPrice){
                        extraPrice = ab.extraPrice;
                        realExtraPrice = ab.realExtraPrice;
                    }
                    goodsAttributes.push('<input type="number" name="attr-text" value="' + extraPrice + '" class="form-control"  id="' + ab.id + '" attrId="' + v.attrId + '" attrValue="' + o + '" required="" aria-required="true" minlength="1" maxlength="100000"/>');
                    goodsAttributes.push('</div>');
                    goodsAttributes.push('</div>');

                    goodsAttributes.push('<div class="form-group">');
                    goodsAttributes.push('<div class="col-sm-10">');
                    goodsAttributes.push('<input type="number" name="attrExtraPrice"  value="' + realExtraPrice + '"  class="form-control" required="" aria-required="true" minlength="1" maxlength="100000">');
                    goodsAttributes.push('</div>');
                    goodsAttributes.push('</div>');
                    goodsAttributes.push('</div>');
                });
                goodsAttributes.push('</div>');
                goodsAttributes.push('</div>');
            });
            $("#attribute-list").html(goodsAttributes.join(''));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error(errorThrown, textStatus);
        }
    });
}
function checkAndFindAttributeLink(attrId,attrValue){

    var goodsId = $("#goodsId").val();
    var rtn = {id: 0};
    $.each(goodsAttrLink, function (i, v) {
            // console.log(v, v.attrValue, attrValue, v.attrValue == attrValue);
        if(v.attrId == attrId && v.attrValue == attrValue && v.goodsId == goodsId){
            rtn = v;
        }
    });
    return rtn;
}
function deleteImageForGoods(imageId, object) {
    $.ajax(
        {
            url: Config.deleteAlbumUrl + "/" + imageId,
            type: "DELETE",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
                $(object).parent().remove();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    return false;
}
function setImageForGoods(imageId, object) {
    $.ajax(
        {
            url: Config.updateUrl,
            type: "PUT",
            data: {goodsId: $("#goodsId").val(), goodsThum: $("img", $(object).parent()).attr('src')},
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    return false;
}
